package com.black.knight.chess;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.black.knight.chess.calls.FacebookLoginOrRegisterUserCall;
import com.black.knight.chess.calls.LoginUserCall;
import com.black.knight.chess.common.User;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.model.SettingsModel;
import com.black.knight.chess.utils.Utils;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;

public class SignInActivity extends Activity{

	private SignInActivity context;
	
	public static User user;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        
    	this.context = this;
    	
    	Utils.setLanguage(SettingsModel.getInstance().getLanguage(), context);
    	
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        refresh(getResources().getConfiguration());
        
        setTitle(context.getResources().getString(R.string.signin));
    }
    
    public void refresh(Configuration config) {             	
    	if(config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    		setContentView(R.layout.signin);
    	} else {
    		setContentView(R.layout.signin_vertical);
    	}
    	
    	final ImageButton registrationButton = (ImageButton) findViewById(R.id.registrationButton);
        final ImageButton signinbutton = (ImageButton) findViewById(R.id.signinbutton);
        
        final EditText usernameInputField = (EditText) findViewById(R.id.usernameInputField);
        final EditText passwordInputField = (EditText) findViewById(R.id.passwordInputField);
        final CheckBox autoLogIncheckBox = (CheckBox) findViewById(R.id.autoLogIncheckBox);
        
        autoLogIncheckBox.setChecked(SettingsModel.getInstance().isAutoLogIn() || SettingsModel.getInstance().isAutoLogInWithFacebook());
        
        if(SettingsModel.getInstance().isAutoLogIn()) {
        	usernameInputField.setText(SettingsModel.getInstance().getUsername());
        	passwordInputField.setText(SettingsModel.getInstance().getPassword());
        }
        
        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
        
        registrationButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
	        	intent.setClass(context, RegistrationActivity.class);
	        	startActivity(intent);		
			}
		});
        
        final ImageButton facebookButton = (ImageButton) findViewById(R.id.facebookButton);
        
        facebookButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final Facebook facebook = SahModel.getInstance().facebook;
				
				if(!facebook.isSessionValid()) {
					facebook.authorize(context, new Facebook.DialogListener() {
						@Override
						public void onFacebookError(FacebookError e) {
							Utils.displayAlertMessage(context, getResources().getString(R.string.unable_to_connect_to_server));
						}
						
						@Override
						public void onError(DialogError e) {
							Utils.displayAlertMessage(context, getResources().getString(R.string.unable_to_connect_to_server));
						}
						
						@Override
						public void onComplete(Bundle values) {
							SettingsModel.getInstance().setFacebookToken(facebook.getAccessToken());
							SettingsModel.getInstance().setFacebookTokenExpiration(facebook.getAccessExpires());
							
							processFacebookUser();
						}
						
						@Override
						public void onCancel() {
						}
					});
				} else {
					processFacebookUser();
				}
			}
		});
        
        signinbutton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String username = usernameInputField.getText().toString();
				String password = passwordInputField.getText().toString();
				Boolean autoLogIn = autoLogIncheckBox.isChecked();
				
				if(username.length() < 6) {
					usernameInputField.setError(context.getResources().getString(R.string.username_too_short));					
				} else {
					usernameInputField.setError(null);
				}
				
				if(password.length() < 6) {
					passwordInputField.setError(context.getResources().getString(R.string.password_too_short));					
				} else {
					passwordInputField.setError(null);
				}
				
				if(usernameInputField.getError() == null && passwordInputField.getError() == null) {
					progressBar.setVisibility(ProgressBar.VISIBLE);
					
					user = new User();
					user.setUsername(username);
					user.setPassword(password);
					
					LoginUserCall call = new LoginUserCall(user, context);
					call.setAutoSignIn(autoLogIn);
					
					SettingsModel.EXECUTOR_SERVICE.execute(call);
				}
			}
		});
    }
    
    public void processFacebookUser() {
    	final Facebook facebook = SahModel.getInstance().facebook;
    	
    	try {
			Bundle params = new Bundle();
			params.putString("fields", "id,gender,name,location,bio,picture");
    		String response = facebook.request("me", params);
			
    		JSONObject obj = new JSONObject(response);
    		
    		final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
    		progressBar.setVisibility(ProgressBar.VISIBLE);
    		
    		final CheckBox autoLogIncheckBox = (CheckBox) findViewById(R.id.autoLogIncheckBox);
    		Boolean autoLogIn = autoLogIncheckBox.isChecked();
			
			user = new User();
			user.setUsername(obj.getString("id"));
			
			String gender = obj.getString("gender");
			if(gender.length() > 0) {
				gender = String.valueOf(gender.charAt(0)).toUpperCase() + gender.substring(1);
			}
			user.setGender(gender);
			user.setName(obj.getString("name"));
			user.setAbout(obj.getString("bio"));
			user.setPicture(obj.getString("picture"));
			user.setType(1);
			
			user.setCity(((JSONObject)obj.get("location")).getString("name"));
			
			FacebookLoginOrRegisterUserCall call = new FacebookLoginOrRegisterUserCall(user, context);
			call.setAutoSignIn(autoLogIn);
			
			SettingsModel.EXECUTOR_SERVICE.execute(call);
		} catch (Exception e) {
			Utils.displayAlertMessage(context, getResources().getString(R.string.unable_to_connect_to_server));
		}
    }
    
    public void onResume() {    
        super.onResume();
        
        final Facebook facebook = SahModel.getInstance().facebook;
        facebook.extendAccessTokenIfNeeded(this, null);
    }
    
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
        Utils.setLanguage(SettingsModel.getInstance().getLanguage(), context);
      
        refresh(getResources().getConfiguration());
        
        super.onConfigurationChanged(newConfig);
    }
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        SahModel.getInstance().facebook.authorizeCallback(requestCode, resultCode, data);
    }
}